package online.westonline.com.westonline.ui.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.easy.west.westclient.Constants;
import com.easy.west.westclient.api.login.bean.User;
import com.jaeger.library.StatusBarUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.model.UserInfo;
import cn.nekocode.badge.BadgeDrawable;
import de.hdodenhof.circleimageview.CircleImageView;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.base.BaseFragment;
import online.westonline.com.westonline.event.PushNotifyEvent;
import online.westonline.com.westonline.ui.AvatorActivity;
import online.westonline.com.westonline.ui.GaideActivity;
import online.westonline.com.westonline.ui.LoginActivity;
import online.westonline.com.westonline.ui.MessageActivity;
import online.westonline.com.westonline.ui.QeActivity;
import online.westonline.com.westonline.utils.CacheUtils;
import online.westonline.com.westonline.utils.QRCodeUtil;
import online.westonline.com.westonline.utils.ToastUtils;
import online.westonline.com.westonline.utils.UiUtlis;

/**
 * 通讯录
 * Created by xiatao on 2018/7/31.
 */

public class ConstactFragment extends BaseFragment {


    @BindView(R.id.img_my_avator)
    CircleImageView imgMyAvator;
    @BindView(R.id.tv_me_full_name)
    TextView tvMeFullName;
    @BindView(R.id.tv_my_eq)
    TextView tvMyEq;
    @BindView(R.id.li_eq_parse)
    LinearLayout liEqParse;
    @BindView(R.id.img_me_message_count)
    ImageView imgMeMessageCount;
    @BindView(R.id.right_icon_me)
    ImageView rightIconMe;
    @BindView(R.id.li_my_message)
    LinearLayout liMyMessage;
    @BindView(R.id.img_me_meeting_count)
    ImageView imgMeMeetingCount;
    @BindView(R.id.right_icon_meeting)
    ImageView rightIconMeeting;
    @BindView(R.id.li_my_meetroom)
    LinearLayout liMyMeetroom;
    @BindView(R.id.img_me_notice_count)
    ImageView imgMeNoticeCount;
    @BindView(R.id.right_icon_notice)
    ImageView rightIconNotice;
    @BindView(R.id.li_my_important_notice)
    LinearLayout liMyImportantNotice;
    @BindView(R.id.img_me_manange_count)
    ImageView imgMeManangeCount;
    @BindView(R.id.right_icon_manange)
    ImageView rightIconManange;
    @BindView(R.id.li_my_manange_check)
    LinearLayout liMyManangeCheck;
    @BindView(R.id.img_me_gaide_count)
    ImageView imgMeGaideCount;
    @BindView(R.id.right_icon_gaide)
    ImageView rightIconGaide;
    @BindView(R.id.li_my_manange_gaide)
    LinearLayout liMyManangeGaide;
    @BindView(R.id.btn_exit_login)
    TextView btnExitLogin;
    Unbinder unbinder;
    private User me;
    //在app开启过后的新消息数量
    private int newcount;
    private View view;
    private Dialog dialog_eq;
    TextView tvDialogName;
    LinearLayout liProgressview;
    ImageView imgEq;
    TextView tvSave;
    ImageView imgEqhead;
    private Bitmap bitmap;
    private Bitmap img_avator_bitmap;
    private boolean is_head_loadindown=false;
    @Override
    protected boolean setEventOpen() {
        return false;
    }

    @Override
    protected void initdata() {
        //获取用户
        me = CacheUtils.getInstance().getUser();
        //设置状态栏
        StatusBarUtil.setTranslucent(this.activity);
    }

    @Override
    protected void initview() {

        initdialog();
        tvMeFullName.setText(me.getData().getName());
        //设置头像
        final UserInfo userInfo = JMessageClient.getMyInfo();
        userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
            @Override
            public void gotResult(int i, String s, Bitmap bitmap) {
                if (i == 0) {
                    imgMyAvator.setImageBitmap(bitmap);
                    is_head_loadindown = true;
                    img_avator_bitmap = toRoundBitmap(bitmap);
                    imgEqhead.setImageBitmap(bitmap);
                } else {
                    //从服务器上获取
                    userInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
                        @Override
                        public void gotResult(int i, String s, Bitmap bitmap) {
                            if (i == 0) {
                                img_avator_bitmap =  toRoundBitmap(bitmap);
                                imgEqhead.setImageBitmap(bitmap);
                                is_head_loadindown = true;
                                imgMyAvator.setImageBitmap(bitmap);
                                Log.e("消息","头像设置完成");
                            } else {
                                ToastUtils.showToast("头像获取失败:" + s);
                            }
                        }
                    });
                }
            }
        });
        initsession();
    }
    /**
     * 利用浮动工具窗代替
     */
    private void initdialog() {
        dialog_eq = new Dialog(activity);
        view = View.inflate(activity, R.layout.eq_dialogview, null);
        dialog_eq.setContentView(view);
        dialog_eq.setCancelable(true);
        // 获得当前activity所在的window对象
        Window window = dialog_eq.getWindow();
        WindowManager m = getActivity().getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.5); // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.65，根据实际情况调整
        window.setAttributes(p);
        tvDialogName = view.findViewById(R.id.tv_dialog_name);
        liProgressview = view.findViewById(R.id.li_progressview);
        imgEq = view.findViewById(R.id.img_eq);
        tvSave = view.findViewById(R.id.tv_save);
        imgEqhead = view.findViewById(R.id.img_eq_head);

    }
    /**
     * 初始化事件
     */
    private void initsession() {
        //执行退出操作
        btnExitLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNormalDialog(false, "提示", "是否退出登录"
                        , "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                CacheUtils.getInstance().removeuser();
                                //极光退出(停止推送)
                                JPushInterface.stopPush(activity);
                                JMessageClient.logout();
                                //不移除密码和用户名
                                startActivity(LoginActivity.class, true);
                            }
                        });
            }
        });
        //前往模板中心
        liMyManangeGaide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(GaideActivity.class, false);
            }
        });
        //前往消息界面
        liMyMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(MessageActivity.class,false);
            }
        });
        //二维码生成
        liEqParse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                bitmap =  QRCodeUtil.createQRCodeBitmap(user.getData().getPhonenum()+":"+user.getData().getName(),1000);
                if (is_head_loadindown)
                {
                   bitmap = QRCodeUtil.createQRCodeBitmap(user.getData().getPhonenum()+":"+user.getData().getName()
                   ,1000,img_avator_bitmap,0.2f);
                }
                imgEq.setImageBitmap(bitmap);
                tvDialogName.setText(user.getData().getName());
                dialog_eq.show();
            }
        });
        //保存二维码至本地
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveBitmap();
            }
        });
        //sao
        tvMyEq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(QeActivity.class, false);
            }
        });
        //更改头像
        imgMyAvator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AvatorActivity.class,false);
            }
        });

    }

    /**
     * 圆形
     * @param bitmap
     * @return
     */
    public Bitmap toRoundBitmap(Bitmap bitmap) {
        // 前面同上，绘制图像分别需要bitmap，canvas，paint对象
        bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
        Bitmap bm = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // 这里需要先画出一个圆
        canvas.drawCircle(200, 200, 200, paint);
        // 圆画好之后将画笔重置一下
        paint.reset();
        // 设置图像合成模式，该模式为只在源图像和目标图像相交的地方绘制源图像
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, 0, 0, paint);
        return bm;
    }
    /**
     * 保存二维码
     */
    private void saveBitmap() {

        String path = Constants.CONSTACTS_HEAD;
        //先创建目录
        File file = new File(path);
        if (!file.exists())
        {
            file.mkdirs();
        }
        try {
            File file1 = new File(path,user.getData().getPhonenum()+"_er"+".jpeg");
            FileOutputStream outputStream = new FileOutputStream(file1);
            bitmap.compress(Bitmap.CompressFormat.JPEG,90,outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        ToastUtils.showToast("保存成功");
    }
    /**
     * 加载数据
     */
    private void configrecyclerview() {

    }

    @Override
    protected int setlayout() {
        return R.layout.fragment_constact;
    }

    /**
     *更新角标
     *已在activity实现
     * @param event
     *
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void recivepush(PushNotifyEvent event) {
        newcount = newcount + 1;
        BadgeDrawable badgeDrawable = new BadgeDrawable.Builder()
                .type(BadgeDrawable.TYPE_NUMBER)
                .number(newcount)
                .badgeColor(UiUtlis.getColor(R.color.TopicItemNodeTextColor))
                .textSize(36)
                .build();
        imgMeMessageCount.setBackgroundDrawable(badgeDrawable);
    }
    */

    /***
     * 更新角标,作为初始角标
     * @param count
     */
    public void updateCount(int count) {
        newcount = count;
        if (count>0)
        {
            imgMeMessageCount.setVisibility(View.VISIBLE);
            //先显示一下
            BadgeDrawable badgeDrawable = new BadgeDrawable.Builder()
                    .type(BadgeDrawable.TYPE_NUMBER)
                    .number(newcount)
                    .badgeColor(UiUtlis.getColor(R.color.TopicItemNodeTextColor))
                    .textSize(36)
                    .build();
            imgMeMessageCount.setBackgroundDrawable(badgeDrawable);
        }
        else
        {
            imgMeMessageCount.setVisibility(View.GONE);
        }

    }
}
